package com.example.first.thread;

import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author LSQ
 * @Description 练习 synchronized 加 runnable
 * @date 2021/11/5 21:43
 * @Version 1.0
 */

public class Worker1 implements Runnable {

    private People people;
    private CountDownLatch countDownLatch;
    private ReentrantLock reentrantLock = new ReentrantLock(true);

    public Worker1(People people, CountDownLatch countDownLatch) {
        this.people = people;
        this.countDownLatch = countDownLatch;
    }

    public void doService1() {

        try {
            reentrantLock.lock();
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " get lock!! start doService1");

            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //people.walk();
        } finally {

            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " unlock! end doService1");
            reentrantLock.unlock();
        }


    }

    public void doService2() {
        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " start doService2");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //people.playBasketBall();

        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " end doService2");
    }

    @Override
    public void run() {

        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " prepare running..");

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " start running..");

        try {
            reentrantLock.lock();
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " get lock!! before start doService1");
            //doService1();

            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " unlock! after end doService1");
            reentrantLock.unlock();
        }

        // doService2();


        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " end running..");
        countDownLatch.countDown();
    }

}
